<?php
class Manager_Tag
{
	public static function add(array $tags = array())
	{
		$criteria = new Criteria();

		try {
			$tags = self::clean($tags);
			$objects = array();
			
			foreach ($tags as $tag) {
				$criteria->clear();
				$criteria->add(TagsPeer::NAME, $tag, Criteria::EQUAL);
				
				if (TagsPeer::doCount($criteria) === 0) {
					// add new tag
					$newTag = new Tags();
					$newTag->setName($tag);
					$newTag->save();
					
					$objects[] = $newTag;
				} else {
					$objects[] = TagsPeer::doSelectOne($criteria);
				}
			}
			
			return $objects;
		} catch (Exception $e) {
			throw new Exception('Could not add new tag: ' . $tag . ' ' . $e->getMessage());
		}
	}
	
	public static function clean($tag)
	{
		if (is_array($tag)) {
			$newArray = array();
			
			foreach ($tag as $name) {
				$newArray[] = strtolower(strip_tags(trim($name)));
			}
			
			return $newArray;
		}
		
		return strtolower(trim(strip_tags($tag)));
	}
	
	/**
	 * 
	 * @param $string
	 * @return array of strings/tags
	 */
	public static function fromString($string)
	{
		$first = explode(',', $string);
		
		if (empty($first)) {
			return array();
		}

		//$first = array_unique($first, SORT_STRING); // for new php
		$first = array_unique($first);
		
		$tmp = array();
			//var_dump($first);	
		foreach ($first as $tags) {
			$spaces = explode(' ', $tags);
			$tmp = array_merge($tmp, $spaces);
		}
		
		$all = array();
		
		foreach ($tmp as $tag) {
			$clean = self::clean($tag);
			if (!empty($clean)) {
				$all[] = $clean;
			}
		}
		
		//return array_unique($all, SORT_STRING); // for new php
		return array_unique($all);
	}
}